package com.chaihu.service.configuration;

import com.chaihu.core.base.constants.CommonConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 前台提交乱码解决
 */
@Configuration
public class CustomMVCConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(
                Charset.forName("UTF-8"));
        converter.setWriteAcceptCharset(false);
        return converter;
    }

    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }

    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 可添加多个，这里选择拦截所有请求地址，进入后判断是否有加注解即可
        registry.addInterceptor(new HandlerInterceptorAdapter() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                MDC.put("uuid", UUID.randomUUID().toString().replaceAll("\\-", ""));

                if (request.getAttribute("claims") != null) {
                    Map<String, String> param = (Map<String, String>) request.getAttribute("claims");
                    MDC.put(CommonConstant.LOGIN_USER_ID, param.get(CommonConstant.LOGIN_USER_ID));
                }
                if (request.getHeader("user-id") != null || request.getHeader("user_id") != null) {
                    MDC.put(CommonConstant.LOGIN_USER_ID, StringUtils.isNotBlank(request.getHeader("user-id"))?request.getHeader("user-id"):request.getHeader("user_id"));
                }
                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                super.afterCompletion(request, response, handler, ex);
                MDC.remove("uuid");
                MDC.remove(CommonConstant.LOGIN_USER_ID);
            }
        }).addPathPatterns("/**");
    }
}
